package com.vhall.autotest.api_test.common;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpUtil {
	private HttpPost addHeader(HttpPost post) {

		post.addHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
		post.addHeader("Connection", "keep-alive");
		// post.addHeader("Content-Length", "32");
		post.addHeader("Accept", "*/*");
		post.addHeader("X-Requested-With", "XMLHttpRequest");
		post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

		// Referer: http://t.vhall.com/205290697
		// Accept-Encoding: gzip, deflate
		// Accept-Language: zh-CN,zh;q=0.8,en;q=0.6

		// List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		// nvps.add(new BasicNameValuePair("idlist", "141188289984412349"));
		// httpPost.setEntity(new UrlEncodedFormEntity(nvps));
//		Header[] heads = post.getAllHeaders();
//		for (Header h : heads) {
//			System.out.println("header:" + h.getName() + " " + h.getValue());
//		}
		return post;
	}

	public Map<String, String> requestByPostMethod(String url, Map<String, String> param) {
		CloseableHttpClient httpClient = getHttpClient();
		Map<String, String> result = new HashMap<String, String>();
		try {
			HttpPost post = new HttpPost(url);
			addHeader(post);
			if(param != null){
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				for(Iterator<Map.Entry<String, String>> iterator = param.entrySet().iterator();iterator.hasNext();){
					Map.Entry<String, String> entry = iterator.next();
					list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, "UTF-8");
				post.setEntity(uefEntity);
			}
			
			System.out.println("POST:" + post.getURI());

			CloseableHttpResponse response = null;
			try {
				response = httpClient.execute(post);
//				System.out.println(response);
				HttpEntity entity = response.getEntity();
//				System.out.println("----------------------------------------" + entity + " " + entity.getContentLength());
				String resultText = new String(EntityUtils.toByteArray(entity), "utf-8");
//				System.out.println(resultText);
//				System.out.println(UnicodeDecoder.decode(resultText));
				result.put("resultText", resultText);
				result.put("statusCode", String.valueOf(response.getStatusLine().getStatusCode()));
//				System.out.println("----------------------------------------");
//				System.out.println(response.getStatusLine().getStatusCode());
//				System.out.println(response.getStatusLine().toString());
//				System.out.println(response.getLastHeader("Content-Type"));
				Header headers[] = response.getAllHeaders();
				int i = 0;
				while (i < headers.length) {
//					System.out.println(headers[i].getName() + ":  " + headers[i].getValue());
					i++;
				}
//				System.out.println(response.getAllHeaders().toString());
//				System.out.println("----------------------------------------");
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (response != null) {
					response.close();
				}

			}
			

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeHttpClient(httpClient);
		}
		return result;
	}
	
	
	public Map<String, String> test(String url, Map<String, String> param) {
		url = "http://msg02.e.vhall.com:3000/socket.io/?token=iOiJIUzI1NiJ9.eyJpZCI6IjMwNzE2IiwibmFtZSI6Ilx1NmUzOFx1NWJhMjQ3MjYwNjUzNSIsInJvb20iOiI2OTgwNTgwNjEiLCJyb2xlIjoidXNlciIsInVpZCI6bnVsbCwidHJhY2tJZCI6MTM0NDU1fQ.VGN-NKBa8q6Mg-BRZQLkbOCo_wWMVCChbmq3rhQPbm0&EIO=3&transport=websocket";
		CloseableHttpClient httpClient = getHttpClient();
		Map<String, String> result = new HashMap<String, String>();
		try {
			HttpGet post = new HttpGet(url);
			
			
			
			
//			post.addHeader("GET", "/socket.io/?token=iOiJIUzI1NiJ9.eyJpZCI6IjMwNzE2IiwibmFtZSI6Ilx1NmUzOFx1NWJhMjQ3MjYwNjUzNSIsInJvb20iOiI2OTgwNTgwNjEiLCJyb2xlIjoidXNlciIsInVpZCI6bnVsbCwidHJhY2tJZCI6MTM0NDU1fQ.VGN-NKBa8q6Mg-BRZQLkbOCo_wWMVCChbmq3rhQPbm0&EIO=3&transport=websocket HTTP/1.1");
			post.addHeader("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
			post.addHeader("Host", "msg02.e.vhall.com:3000");
			post.addHeader("Origin", "http://e.vhall.com");
			post.addHeader("Connection", "keep-alive");
			post.addHeader("Accept", "*/*");
			post.addHeader("X-Requested-With", "XMLHttpRequest");
			post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			post.addHeader("Sec-WebSocket-Version","13");
			post.addHeader("Sec-WebSocket-Extensions","permessage-deflate");
			post.addHeader("Sec-WebSocket-Key","AU3zEaMR7BN9UR+kbRyclQ==");
			
			post.addHeader("Connection","keep-alive, Upgrade");
			post.addHeader("Pragma","no-cache");
			post.addHeader("Cache-Control","no-cache");
			post.addHeader("Upgrade","websocket");
			
			System.out.println("GET:" + post.getURI());

			CloseableHttpResponse response = null;
			try {
				response = httpClient.execute(post);
				HttpEntity entity = response.getEntity();
//				System.out.println("----------------------------------------");
				String resultText = new String(EntityUtils.toByteArray(entity), "utf-8");
//				System.out.println(resultText);
//				System.out.println(UnicodeDecoder.decode(resultText));
				result.put("resultText", resultText);
				result.put("statusCode", String.valueOf(response.getStatusLine().getStatusCode()));
//				System.out.println("----------------------------------------");
//				System.out.println(response.getStatusLine().getStatusCode());
//				System.out.println(response.getStatusLine().toString());
//				System.out.println(response.getLastHeader("Content-Type"));
				Header headers[] = response.getAllHeaders();
				int i = 0;
				while (i < headers.length) {
//					System.out.println(headers[i].getName() + ":  " + headers[i].getValue());
					i++;
				}
//				System.out.println(response.getAllHeaders().toString());
//				System.out.println("----------------------------------------");
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (response != null) {
					response.close();
				}

			}
			

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeHttpClient(httpClient);
		}
		return result;
	}
	
	public void upload(String url, Map<String, String> param) {  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try {  
            HttpPost httppost = new HttpPost(url);  
  
            FileBody bin = new FileBody(new File(param.get("image")));  
//            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);  
  
//            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();  
            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("image", bin).addTextBody("webinar_id", param.get("webinar_id")).build();  
            httppost.setEntity(reqEntity);  
  
            CloseableHttpResponse response = httpclient.execute(httppost);  
            try {  
                System.out.println(response.getStatusLine());  
                HttpEntity resEntity = response.getEntity();  
				String resultText = new String(EntityUtils.toByteArray(resEntity), "utf-8");
				System.out.println(resultText);
                if (resEntity != null) {  
                    System.out.println("Response content length: " + resEntity.getContentLength());  
                }  
                EntityUtils.consume(resEntity);  
            } finally {  
                response.close();  
            }  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  

	private CloseableHttpClient getHttpClient() {
		return HttpClients.createDefault();
	}

	private void closeHttpClient(CloseableHttpClient client) {
		if (client != null) {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		System.out.println(new HttpUtil().test(null, null));

	}
	
}
